package tcp

import (
	"fmt"
	"log"
	"net"
)

type TcpServer struct {
	listener    net.Listener
	chan_accept chan net.Conn
	closed      bool
	func_conn   FuncTcpConn
}

type FuncTcpConn func(net.Conn)

func Listen(addr string, func_conn FuncTcpConn) *TcpServer {
	defer fmt.Printf("建立tcp监听成功: %s\n", addr)
	// readBufSize = 1024 * 1024
	// writeBufSize = 1024 * 1024
	tcp_server := &TcpServer{
		chan_accept: make(chan net.Conn, 100),
		closed:      false,
		listener: func() net.Listener {
			listener, err := net.Listen("tcp", addr)
			if err != nil {
				log.Fatal(err)
				return nil
			}
			return listener
		}(),
		func_conn: func_conn,
	}

	go runAccept(tcp_server)
	return tcp_server
}

func runAccept(server *TcpServer) {
	if server == nil {
		return
	}
	defer server.listener.Close()
	for {
		conn, err := server.listener.Accept()
		if err != nil {
			log.Print(err)
			server.closed = true
			break
		}

		if server.func_conn != nil {
			server.func_conn(conn)
		} else {
			server.chan_accept <- conn
		}
	}
}

func Close(server *TcpServer) {
	server.listener.Close()
	close(server.chan_accept)
	server.closed = true
}

func CloseConn(conn net.Conn) {
	conn.Close()
}

func TcpConnect(server *TcpServer) net.Conn {
	return <-server.chan_accept
}
